package com.oops.consumer;

import com.oops.constants.Constants;
import com.oops.mapper.TOrderMapper;
import com.oops.model.TOrder;
import com.oops.service.GoodsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.locks.ReentrantLock;

/**
 * TODO: 定时队列（延迟队列）监听器
 *
 * @author wuyijie
 * @date 2022/4/16 19:19
 */
@Slf4j
@Component
@RocketMQMessageListener(topic = "order_delay", consumerGroup = "group_3")
public class OrderDelayListener implements RocketMQListener<Map> {

    private final StringRedisTemplate redisTemplate;
    private final TOrderMapper tOrderMapper;
    private final GoodsService goodsService;

    private final ReentrantLock lock = new ReentrantLock(true);


    public OrderDelayListener(StringRedisTemplate redisTemplate, TOrderMapper tOrderMapper, GoodsService goodsService) {
        this.redisTemplate = redisTemplate;
        this.tOrderMapper = tOrderMapper;
        this.goodsService = goodsService;
    }

    /**
     * TODO: 对延迟队列中未支付订单商品，做库存对添加
     *
     * @param map 参数
     * @author wuyijie
     * @date 2022/4/16 19:20
     */
    @Override
    public void onMessage(Map map) {
        log.info("延迟接受消息：{}", map);
        lock.lock();
        try {
            TOrder tOrder = tOrderMapper.selectById(Long.parseLong(map.get("orderId").toString()));
            if (Objects.nonNull(tOrder) && !Objects.equals(2, tOrder.getState())) {
                // 增加商品库存
                String goodsId = map.get("goodsId").toString();
                goodsService.increaseGoodsInventory(Long.parseLong(goodsId));
                // 增加商品缓存中的库存
                redisTemplate.opsForValue().increment(Constants.SECKILL_GOODS_PREFIX + goodsId, 1L);
                log.info("商品ID:{}的商品库存增加成功", goodsId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
